/*一些基础的js方法，基础的业务js方法在lib.js里*/
//日期格式化
Date.prototype.format = function (format) {
    var d = this, o = {
        "M+": d.getMonth() + 1,
        "d+": d.getDate(),
        "H+": d.getHours(),
        "m+": d.getMinutes(),
        "s+": d.getSeconds(),
        w: ["日", "一", "二", "三", "四", "五", "六"][d.getDay()]
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length))
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length))
        }
    }
    return format
};

var Common = {
    ctxPath: "",
    version: "",
    businessType: {
        /**
         *人才表
         */
        industrialTalents: "1",

        /**
         *预备人才
         */
        preparatoryTalent: "2",

        /**
         * 购房表
         */
        BUYHOUSE: "3",

        /**
         *技能奖励
         */
        skill: "4",

        /**
         *专业奖励
         */
        professionalTechnology: "5",

        /**
         *租房补贴
         */
        renting: "6",

        /**
         *博士后在站补贴
         */
        doctoralSubsidy: "7",

        /**
         *博士后出站补贴
         */
        outboundSubsidy: "8",

        /**
         *高层次人才
         */
        highlevelTalents: "9",

        /**
         *站点经费
         */
        siteFunds: "10",

        /**
         *离职表
         */
        quit: "11",


        /**
         *入职表
         */
        entry: "12",

        /**
         *关键信息
         */
        keyInformation: "13",

        /**
         *健康体检表
         */
        medicalCare: "14",

        /**
         *健康保险
         */
        insurance: "15",

        /**
         *绿色就医通道
         */
        greenTreatment: "16",

    },

    ProcessCols : [ [ // 表头
        {
            type : 'checkbox',
            fixed:'left',
        },

        {

            field : 'businessState',
            title : '业务状态',
            width : "120",
        },

        {

            field : 'processTime',
            title : '处理时间',
            width : "180",
        },
        {

            field : 'processUserName',
            title : '处理人',
            width : "120",
        },

        {

            field : 'handlingSuggestion',
            title : '处理意见',
            width : "150",
        },
        {

            field : 'processResult',
            title : '审核结果',
            width : "120",
        }

    ] ],
    validAll: function (f) {
        var allCheckBox = $(".validCheckBox");
        var result = true;
        allCheckBox.each(function () {
            var state = $(this).prop("checked");
            result = result & state;
            if (state == false) {
                $(this).focus();
            }

        });

        if (result == true) {
            f();
        } else {
            Common.info("必须勾选所有检查确认框");
        }
        return result;
    },

    fileRequire: function(tbodyId){
        var tbody = $(tbodyId);
        var children = tbody.children('tr');
        var isEmpty = children.length == 0;
        var haveUpload = true;
        children.each(function(){
            var tds = $(this).children();
            var state = tds.eq(1).html();
            haveUpload = haveUpload && (state == '<span style="color: #5FB878;">上传成功</span>')
        });
        /*
        如果为空 或者 没有上传文件
         */
        var isEmpty = isEmpty || !haveUpload;
        return isEmpty;
    },
    log: function (info) {
        console.log(info);
    },
    alert: function (info, iconIndex) {
        parent.layer.msg(info, {
            icon: iconIndex
        });


    },
    info: function (info) {
        Common.alert(info, 0);
    },
    success: function (info) {
        Common.alert(info, 1);
    },
    error: function (info) {
        Common.openConfirm(info)
    },
    post: function (url, paras, next) {
        var index = layer.load(1, {
            shade: [0.5,'#000'] //0.1透明度的背景
        });
        $.ajax({
            url: Common.ctxPath + url,
            type: "POST",
            data: paras,
            success: function (rsp) {
                if (rsp.code != 0) {
                    Common.error(rsp.msg);

                } else {
                    //成功
                    if (next != null) {
                        next(rsp.data);
                    } else {
                        Common.success(rsp.responseJSON.msg);
                    }
                }
                layer.close(index);
            },
            error: function (rsp) {
                Common.error(rsp.responseJSON.msg);
            }
        })

    },

    postWithErrorCallBack: function (url, paras, next, errorCallBack) {
        var index = layer.load(1, {
            shade: [0.5,'#000'] //0.1透明度的背景
        });
        $.ajax({
            url: Common.ctxPath + url,
            type: "POST",
            data: paras,
            success: function (rsp) {
                if (rsp.code != 0) {
                    errorCallBack();
                    Common.error(rsp.msg);

                } else {
                    //成功
                    if (next != null) {
                        next(rsp.data);
                    } else {
                        Common.success(rsp.responseJSON.msg);
                    }
                }
                layer.close(index);
            },
            error: function (rsp) {
                errorCallBack();
                Common.error(rsp.responseJSON.msg);
            }
        })

    },

    getOneFromTable: function (layuiTable, tableId) {
        var checkStatus = layuiTable.checkStatus(tableId)
            , data = checkStatus.data;
        if (data.length == 0) {
            Common.info("请选中一条记录");
        } else if (data.length > 1) {
            Common.info("只能选中一条记录")
        } else {
            return data[0];
        }
    },
    getTalentSum: function (layuiTable, tableId) {
        var checkStatus = layuiTable.checkStatus(tableId)
            , data = checkStatus.data;
        if (data.length == 0) {
            Common.info("请选中一条记录");
        } else {
            return data;
        }
    },
    UnableToFirstTrial: function (layuiTable, tableId) {
        var checkStatus = layuiTable.checkStatus(tableId)
            , data = checkStatus.data;
        if (data.length == 0) {
            Common.info("请选中一条记录");
        } else if (data.length > 1) {
            Common.info("只能选中一条记录")
        } else if (data[0].businessStateCode == 2) {
            Common.info("企业账号无法受理"+data[0].businessState+"的数据")
        } else if (data[0].businessStateCode == 4) {
            Common.info("企业账号无法受理"+data[0].businessState+"的数据")
        } else {
            return data[0];
        }
    },
    getObtainState: function (layuiTable, tableId) {
        var checkStatus = layuiTable.checkStatus(tableId)
            , data = checkStatus.data;
        if (data.length == 0) {
            Common.info("请选中一条记录");
        } else if (data.length > 1) {
            Common.info("只能选中一条记录")
        } else if (data[0].businessState != "待上报" && data[0].businessState != "已退回,待上报") {
            Common.info("已上报,无法修改")
        } else {
            return data[0];
        }
    },
    getMoreDataFromTable: function (layuiTable, tableId) {
        var checkStatus = layuiTable.checkStatus(tableId)
            , data = checkStatus.data;
        var del = false;
        if (data.length == 0) {
            Common.info("请选中记录");
        } else {
            for (i = 0; i < data.length; i++) {
                if (data[i].businessState == "待初核") {
                    Common.info("包含待初核数据,无法删除");
                    del = true;
                    break;
                }else if (data[i].businessState == "待受理") {
                    Common.info("包含待受理数据,无法删除");
                    del = true;
                    break;
                } else if (data[i].businessState == "待复核") {
                    Common.info("包含待复核数据,无法删除");
                    del = true;
                    break;
                } else if (data[i].businessState == "业务生效") {
                    Common.info("包含业务生效数据,无法删除");
                    del = true;
                    break;
                }
            }
            if (del == false) {
                return data;
            }
        }
    },
    getDelInvalid: function (layuiTable, tableId) {//用于删除失效用户
        var checkStatus = layuiTable.checkStatus(tableId)
            , data = checkStatus.data;
        var i;
        var judge = true;
        if (data.length == 0) {
            Common.info("请选中记录");
        } else {
            for (i = 0; i < data.length; i++) {
                if (data[i].state == "S1") {
                    Common.info("请先设置【状态】禁用，在删除");
                    judge = false;
                }
            }
            if (judge)
                return data;
        }
    },
    getDelete: function (layuiTable, tableId) {
        var checkStatus = layuiTable.checkStatus(tableId)
            , data = checkStatus.data;
        var del = false;
        if (data.length == 0) {
            Common.info("请选中记录");
        } else {
            for (i = 0; i < data.length; i++) {
                if (data[i].state == "正常") {
                    Common.info("请先设置【状态】禁用，在删除");
                    del = true;
                }
            }
            if (del == false) {
                return data;
            }
        }
    },
    openDlg: function (url, title) {
        var index = layer.open({
            type: 2,
            content: Common.ctxPath + url,
            title: title,
            maxmin: false
        });
        layer.full(index);
    },
    openPreview: function (url, title) {
        if(url == null || url == ''){
            Common.info("无数据");
            return;
        }
        var widhtSize = $(window).width(); //浏览器当前可视区域宽度
        var heightSize = $(window).height(); //浏览器当前可视区域高度
        var index = layer.open({
            title:title,
            type: 2,
            content: url,
            area: [widhtSize/2-100+'px', heightSize-30+'px'],
            maxmin: true
        });
    },
    topOpenDlg: function (url, title) {
        var index = top.layer.open({
            type: 2,
            content: Common.ctxPath + url,
            title: title,
            area: ['100%', '100%'],
            maxmin: false
        });
        layer.full(index);
    },
    openConfirm: function (content, callback, callBackNo) {
        var index = layer.confirm(content, {
            btn: ['确认', '取消'] //按钮
        }, function () {
            if (callback != null) {
                callback();
            }
            layer.close(index);
        }, function () {
            if (callBackNo != null) {
                callBackNo()
            }
            layer.close(index);
        });

    },
    openPrompt: function (title, defaultValue, callback) {
        layer.prompt({title: title, formType: 0, value: defaultValue}, function (value, index, elem) {
            layer.close(index);
            callback(value);
        });
    },
    concatBatchId: function (data, idField) {
        var ids = ""
        var name = idField == null ? "id" : idField;
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            ids = ids + item[name];
            if (i != data.length - 1) {
                ids = ids + ","
            }
        }
        return ids;
    },
    sessionTimeoutRegistry: function () {
        $.ajaxSetup({
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            complete: function (XMLHttpRequest, textStatus) {
                //通过XMLHttpRequest取得响应头，sessionstatus，
                var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
                if (sessionstatus == "timeout") {
                    //如果超时就处理 ，指定要跳转的页面
                    window.location = Common.ctxPath + "/global/sessionError";
                }
            }
        });
    },
    initValidator: function (formId, fields) {
        $('#' + formId).bootstrapValidator({
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: fields,
            live: 'enabled',
            message: '该字段不能为空'
        });
    },
    endWith: function (fileName) {
        //获取.点索引位置
        var index1 = fileName.lastIndexOf(".");
        //获取总长
        var index2=fileName.length;
        var suffix=fileName.substring(index1+1,index2);//后缀名
        if(suffix == "pdf"){
            return true;
        }
        return false;
    },
    getDate: function (date, pattern) {
        if (date == null || date == '') {
            return "";
        } else {
            if (pattern) {
                return new Date(date).format(pattern);
            } else {
                return date.substring(0, 10);
            }

        }
    },
    getMoney:function (num) {
        num = (num + '').replace(/[^0-9+-Ee.]/g, '');
        var n = !isFinite(+num) ? 0 : +num,
            prec = !isFinite(+2) ? 0 : Math.abs(2),
            sep = ',',
            dec = '.',
            s = '',
            toFixedFix = function (n, prec) {
                var k = Math.pow(10, prec);
                return '' + Math.ceil(n * k) / k;
            };

        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        var re = /(-?\d+)(\d{3})/;
        while (re.test(s[0])) {
            s[0] = s[0].replace(re, "$1" + sep + "$2");
        }

        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0');
        }
        return s.join(dec);
    }
};

/**
 *  下拉列表排序-数值类型数组排序
 * @param selectObj
 */
function sortRule(a,b) {
    var x = a._text;
    var y = b._text;
    return x-y;
}
function op(){
    var _value;
    var _text;
    var _selected;
}
function sortOption(selectObj){
    var obj = document.getElementById(selectObj);
    var tmp = new Array();
    for(var i=0;i<obj.options.length;i++){
        var ops = new op();
        ops._value = obj.options[i].value;
        ops._text = obj.options[i].text;
        ops._selected = obj.options[i].selected;
        tmp.push(ops);
    }
    tmp.sort(sortRule);
    for(var j=0;j<tmp.length;j++){
        obj.options[j].value = tmp[j]._value;
        obj.options[j].text = tmp[j]._text;
        obj.options[j].selected = tmp[j]._selected;
    }
}

// JQuery方法定制
(function ($) {

    $.ajaxSetup({
        type: 'POST',
        async: true,
        dataType: "json",
        timeout: 30000
    });

    /**
     * 获取form表单数据
     */
    $.fn.getFormData = function (isValid) {
        var fieldElem = $(this).find('input,select,textarea'); //获取所有表单域
        var data = {};
        layui.each(fieldElem, function (index, item) {
            if (!item.name) return;
            if (/^checkbox|radio$/.test(item.type) && !item.checked) return;
            var value = item.value;
            if (item.type == "checkbox") {//如果多选
                if (data[item.name]) {
                    value = data[item.name] + "," + value;
                }
            }
            if (isValid) {
                //如果为true,只需要处理有数据的值
                if (!$.isEmpty(value)) {
                    data[item.name] = value;
                }
            }
            else {
                data[item.name] = value;
            }
        });
        return data;
    };

    $.fn.serializeJson = function () {
        var serializeObj = {};
        var array = this.serializeArray();
        var str = this.serialize();
        $(array).each(
            function () {
                if (serializeObj[this.name]) {
                    if ($.isArray(serializeObj[this.name])) {
                        serializeObj[this.name].push(this.value);
                    } else {
                        serializeObj[this.name] = [
                            serializeObj[this.name], this.value];
                    }
                } else {
                    serializeObj[this.name] = this.value;
                }
            });
        return serializeObj;
    };


    $.extend({
        //非空判断
        isEmpty: function (value) {
            if (value === null || value == undefined || value === '') {
                return true;
            }
            return false;
        },
        //获取对象指
        result: function (object, path, defaultValue) {
            var value = "";
            if (!$.isEmpty(object) && $.isObject(object) && !$.isEmpty(path)) {
                var paths = path.split('.');
                var length = paths.length;
                $.each(paths, function (i, v) {
                    object = object[v];
                    if (length - 1 == i) {
                        value = object;
                    }
                    if (!$.isObject(object)) {
                        return false;
                    }
                })

            }

            if ($.isEmpty(value) && !$.isEmpty(defaultValue)) {
                value = defaultValue;
            }
            return value;
        },
        //判断是否obj对象
        isObject: function (value) {
            var type = typeof value;
            return value != null && (type == 'object' || type == 'function');
        },
        //是否以某个字符开头
        startsWith: function (value, target) {
            return value.indexOf(target) == 0;
        },
        //设置sessionStorage
        setSessionStorage: function (key, data) {
            sessionStorage.setItem(key, data);
        },
        //获取sessionStorage
        getSessionStorage: function (key) {
            return sessionStorage.getItem(key) == null ? "" : sessionStorage.getItem(key);
        },
        //删除sessionStorage
        removeSessionStorage: function (key) {
            sessionStorage.removeItem(key);
        },
        //清除sessionStorage
        clearSessionStorage: function () {
            sessionStorage.clear();
        },
        uuid: function () {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                return v.toString(16);
            });
        }
    });

}(jQuery));

/**
 * JSON转URL参数
 * @param data
 * @returns {string}
 */
function parseParams(data) {
    try {
        var tempArr = [];
        for (var i in data) {
            var key = encodeURIComponent(i);
            var value = encodeURIComponent(data[i]);
            tempArr.push(key + '=' + value);
        }
        var urlParamsStr = tempArr.join('&');
        return urlParamsStr;
    } catch (err) {
        return '';
    }
}
